#include "LunCorrelation.h"
#include <math.h>
#include <map>
#include <vector>

LunCorrelation::LunCorrelation(SystemView* Sys)
{
	sys = Sys;
}

LunCorrelation::~LunCorrelation(){

}

//pre cond : lunId1 and lunId2 exists
double LunCorrelation::calcLunsCorrelation(LUNID lunId1 , LUNID lunId2 , int param){
	double w = 0;
	int timesNum = sys->getNof_time_slices();
	vector<double> vec1 (timesNum ,0);
	vector<double> vec2 (timesNum ,0);
	double sum1 = 0, sum2 = 0 ;

	if(param<1 || param>11)
		return -2;
	
	LunTotalStatistics* total1 , *total2;
	total1 = sys->getLunTotalStatistics(lunId1);// get lun1 total statistics
	total2 = sys->getLunTotalStatistics(lunId2);// get lun2 total statistics
	if(total1==NULL || total2==NULL)
		return -2;

	map<int,LunTimeStatistics*>* lunStats1 = total1->getAllLunTimeStatistics();
	map<int,LunTimeStatistics*>* lunStats2 = total2->getAllLunTimeStatistics();
	map<int,LunTimeStatistics*>::iterator it1 , it2;

	// take 2 relevant vectors V1 V2
	it2 = lunStats2->begin();
	it1 = lunStats1->begin();
	for(int i =0; i<timesNum; i++)
	{
		if(it1 == lunStats1->end())
			vec1[i] = 0;
		else{
			vec1[i] = ((*it1).second->getStatistic(param));
			it1++; 
		}
		if(it2 == lunStats2->end())
			vec2[i] = 0;
		else{
			vec2[i] = ((*it2).second->getStatistic(param));
			it2++;
		}
		if(vec1[i]<0 || vec2[i]<0)
			return -2;
		sum1 += vec1[i];
		sum2 += vec2[i];
	}

	// sub avg and sum the V1i^2 V2i^2
	double avg1 = (sum1/timesNum) , avg2 = (sum2/timesNum);
	sum1 = 0; sum2 = 0;
	for(int i =0; i<timesNum; i++)
	{
		vec1[i] = vec1[i] - avg1;	
		vec2[i] = vec2[i] - avg2;
		sum1 += pow(vec1[i],2); 
		sum2 += pow(vec2[i],2);
	}

	//normalaize V1 V2 and mult vectors
	for(int i =0; i<timesNum; i++)
	{
		if(sum1 && sum2){
			vec1[i] = vec1[i] / sqrt(sum1);
			vec2[i] = vec2[i] / sqrt(sum2);
		}
		w += vec1[i] * vec2[i];
	}

	return w;
}
